package com.anfeng.cms.api.login;

import com.anfeng.cms.api.support.ConstEum;
import com.anfeng.cms.api.support.ResDto;
import com.anfeng.cms.domain.manager.AfManagerInfo;
import com.anfeng.cms.request.manager.LoginReq;
import com.anfeng.cms.request.manager.ManagerUser;
import com.anfeng.cms.service.manager.IAfManagerInfoService;
import com.anfeng.cms.util.CryptoUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author 吴朋
 * @date 2019/7/16
 */
@RestController
public class LoginEndPoint {

    @Autowired
    private IAfManagerInfoService managerInfoService;
    @Autowired
    private HttpServletRequest servletRequest;

    @PostMapping(value = "/api/login")
    @ResponseBody
    public ResDto login(LoginReq req) {
        ResDto resDto;
        if (null == req || StringUtils.isBlank(req.getMobile()) || StringUtils.isBlank(req.getPassword())) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            return resDto;
        }
        // 查询管理员信息
        AfManagerInfo managerInfo = managerInfoService.getManagerInfoByMobile(req.getMobile());
        if (null == managerInfo) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            return resDto;
        }
        String password = managerInfo.getPassword();
        String shaPassword = CryptoUtil.sha256(req.getPassword());
        if (!password.equals(shaPassword)) {
            resDto = new ResDto(ConstEum.PARAM_ERROR);
            return resDto;
        }
        ManagerUser loginUser = new ManagerUser();
        BeanUtils.copyProperties(managerInfo, loginUser);
        // 认证成功
        // 将管理员信息放入session中
        HttpSession session = servletRequest.getSession();
        session.setAttribute("loginUser", loginUser);
        // session最大保存一周
        session.setMaxInactiveInterval(7 * 24 * 3600);
        return new ResDto(ConstEum.SUCCESS);
    }

}
